package com.juc.semaphore.semaphore3;

import java.util.concurrent.Semaphore;

public class Service {
    /**
     * 有参acquire (int permits) 是每调一次此方法就使用x个许可
     * 一共10个许可
     * 一次是semaphore.acquire(2); 每次消耗2个 则 10/2 = 5 一共可以让5个线程同时运行 acquire 和
     * release之间的代码
     */
     Semaphore semaphore = new Semaphore(10);
     public void testMethod(){
         try {
             semaphore.acquire(2);
             System.out.println(Thread.currentThread().getName() + " begin timer " + System.currentTimeMillis());
             int sleepValue = ((int) (Math.random() * 10000));
             System.out.println(Thread.currentThread().getName() + " 停止了 " + (sleepValue / 1000) + "秒");
             Thread.sleep(sleepValue);
             System.out.println(Thread.currentThread().getName() + " end timer " + System.currentTimeMillis());
             semaphore.release(2);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
}
